import { HOUR_MILL } from '../constants';
import { Settings } from '../interface/settings';
import { settings } from '../service/request/settings';

const DEFAULT: Settings = {
    captcha: false,
    withdraw: false,
    poolReward: false,
    tradeTime: 0
}

const SETTINGS = 'SETTINGS'
const overtime = 1 * HOUR_MILL // 2 hour
type SettingsType = { timestamp: number, data: Settings }

const requestSettings = async (): Promise<{ data: Settings, isDefault: boolean }> => {
    const res = await settings();
    if (res.success && res.data) {
        saveData(res.data)
        return {
            data: res.data,
            isDefault: false
        }
    }
    return {
        data: DEFAULT,
        isDefault: true
    }
}

const saveData = (data: Settings): boolean => {
    if (!data) {
        return false
    }

    try {
        window.localStorage.setItem(SETTINGS, JSON.stringify({ timestamp: (new Date().getTime()), data }))
        return true
    } catch (error) {
        return false
    }
}

export const fetchSettings = async (force?: boolean): Promise<Settings> => {
    if (force) {
        const res = await requestSettings();
        if (!res.isDefault) {
            return res.data
        }
        try {
            const str = window.localStorage.getItem(SETTINGS);
            if (str) {
                const json: SettingsType = JSON.parse(str)
                return json.data
            }
        } catch (error) {
            // temp
        }
        return res.data
    }

    try {
        const str = window.localStorage.getItem(SETTINGS);
        if (str) {
            const json: SettingsType = JSON.parse(str)
            if (new Date().getTime() - json.timestamp >= overtime) {
                return (await requestSettings()).data;
            }
            return json.data
        }
        return (await requestSettings()).data;
    } catch (error) {
        return (await requestSettings()).data;
    }
}
